// 导入pages.json配置
import pagesJson from '../pages.json';

// 解析tabBar页面路径
const tabBarPages = pagesJson.tabBar?.list?.map(item => item.pagePath) || [];

// 自动生成路由配置
const generateRoutes = () => {
  return pagesJson.pages.map(page => {
    let name = page.path.split('/').pop();
    
    // 修复：为首页路径特殊指定name为'home'
    if (page.path === 'pages/index/index') {
      name = 'home';
    }
    
    const isTab = tabBarPages.includes(page.path);
    
    return {
      path: `/${name}`,
      name,
      url: page.path,
      isTab,
      title: page.style?.navigationBarTitleText || name
    };
  });
};

// 动态生成的路由配置
export const routes = generateRoutes();

// 路由工具类（修改部分）
export const Router = {
  // 添加前置守卫钩子数组
  beforeEachHooks: [],
  
  // 注册前置守卫
  beforeEach(fn) {
    if (typeof fn === 'function') {
      this.beforeEachHooks.push(fn);
    } else {
      throw new Error('Router.beforeEach requires a function');
    }
  },

  push(options) {
    let url = '';
    let query = {};
    let targetRoute = null;
  
    if (typeof options === 'string') {
      url = options;
    } else {
      if (options.name) {
        targetRoute = routes.find(item => item.name === options.name);
        if (!targetRoute) throw new Error(`Route ${options.name} not found`);
        url = targetRoute.url;
        // Ensure query is always an object
        query = typeof options.query === 'object' && options.query !== null ? options.query : {};
      } else if (options.path) {
        targetRoute = routes.find(item => item.path === options.path);
        url = targetRoute ? targetRoute.url : options.path;
        // Ensure query is always an object
        query = typeof options.query === 'object' && options.query !== null ? options.query : {};
      }
    }
  
    // 构建查询字符串
    const queryStr = Object.keys(query)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
      .join('&');
    if (queryStr) url += `?${queryStr}`;
  
    // 确定是否为tabBar页面
    const isTab = targetRoute ? targetRoute.isTab : routes.some(item => item.url === url.split('?')[0] && item.isTab);
  
    // 构建to和from路由对象
    const to = targetRoute ? {
      path: targetRoute.path,
      name: targetRoute.name,
      url: targetRoute.url,
      query: query,
      isTab: targetRoute.isTab
    } : { path: url.split('?')[0], query: query, isTab };
  
    const pages = getCurrentPages();
    // 修复：确保options始终是对象
    const currentPageOptions = pages.length > 0 ? (pages[pages.length - 1].options || {}) : {};
    const from = pages.length > 0 ? {
      path: `/${pages[pages.length - 1].route}`,
      query: currentPageOptions,
      fullPath: `/${pages[pages.length - 1].route}${Object.keys(currentPageOptions).length ? '?' + new URLSearchParams(currentPageOptions).toString() : ''}`
    } : { path: '/', query: {}, fullPath: '/' };
  
    // 执行前置守卫
    let nextCalled = false;
    const next = (params) => {
      if (nextCalled) return;
      nextCalled = true;
  
      // 1. 如果next被调用且参数为false，则取消跳转
      if (params === false) return;
  
      // 2. 如果next被调用且参数是路径对象，则重定向
      if (typeof params === 'object' && (params.path || params.name)) {
        return this.push(params);
      }
  
      // 3. 正常执行跳转
      if (isTab) {
        uni.switchTab({ url: `/${url.split('?')[0]}` });
      } else {
        uni.navigateTo({ url: `/${url}` });
      }
    };
  
    // 依次执行所有前置守卫
    if (this.beforeEachHooks.length > 0) {
      this.beforeEachHooks.forEach((hook, index) => {
        hook(to, from, next);
      });
    } else {
      // 如果没有守卫，直接执行跳转
      next();
    }
  },

  replace(options) {
    // 实现逻辑类似push，但使用redirectTo
    let url = '';
    let query = {};
    if (typeof options === 'string') {
      url = options;
    } else {
      if (options.name) {
        const route = routes.find(item => item.name === options.name);
        if (!route) throw new Error(`Route ${options.name} not found`);
        url = route.url;
      } else if (options.path) {
        const route = routes.find(item => item.path === options.path);
        url = route ? route.url : options.path;
      }
      // 修复：确保query始终是对象
      query = typeof options.query === 'object' && options.query !== null ? options.query : {};
      const queryStr = Object.keys(query)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
        .join('&');
      if (queryStr) url += `?${queryStr}`;
    }
    uni.redirectTo({ url });
  },

  go(delta = -1) {
    uni.navigateBack({ delta });
  },

  reload() {
    uni.reLaunch({
      url: getCurrentPages()[getCurrentPages().length - 1].route
    });
  }
};

export default Router;